<?php

namespace app\admin\model\course;

use app\admin\model\course\UserCoupon;
use app\common\model\User;
use think\Model;
use think\Validate;


class Coupon extends Model
{
    // 表名
    protected $name = 'coupon';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'type_text',

    ];

    //类型
    const TYPE_FREE = "free"; // 免费券
    const TYPE_PAY = "pay"; // 付费券
    //来源类型列表
    public function getTypeList(){
        return [
            self::TYPE_FREE => "免费券",
            self::TYPE_PAY => "付费券",
        ];
    }

    const STATUS_SEND = 1; //未使用
    const STATUS_USE = 2; //已使用
    const STATUS_EXPIRE = -1; //已过期

    //来源类型列表
    public function getStatusList(){
        return [
            self::STATUS_SEND => "未使用",
            self::STATUS_USE => "已使用",
        ];
    }

    //来源类型列表
    public function getAdminStatusList(){
        return [
            self::STATUS_EXPIRE => "已过期",
            self::STATUS_SEND => "未使用",
            self::STATUS_USE => "已使用",
        ];
    }

    protected static function init()
    {
        self::afterInsert(function ($row) {
            $pk = $row->getPk();
            $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
        });
    }



    public function getTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['type']) ? $data['type'] : '');
        if(isset(self::getTypeList()[$value])){
            return self::getTypeList()[$value];
        }else{
            return '';
        }

    }





    public function addCoupon($params){
        $rule = [
            ["title","require","请填写优惠券名称"],
            ["money","require","请填写满足金额"],
            ["reduction_money","require","请填写减免金额"],
            ["num","require","请填写优惠券总数量"],
            ["day","require","请填写有效期"],
        ];
        if($params['type'] == self::TYPE_PAY){
            $result[] = ["coupon_money","require","请填写优惠券金额"];
            if($params['coupon_money'] <= 0 ){
                exception("价格必须大于0");
            }
        }
        $validate = new Validate($rule);

        $result = $validate->check($params);
        if(!$result){
            exception((string)$validate->getError());
        }
        if($params['money'] <= 0 ){
            exception("满足金额必须大于0");
        }

        if($params['reduction_money'] <= 0 ){
            exception("减免金额必须大于0");
        }
        if($params['money'] <= $params['reduction_money'] ){
            exception("满足金额必须大于减免金额");
        }
        if($params['num'] <= 0 ){
            exception("总数量必须大于0");
        }
        if($params['day'] <= 0 ){
            exception("有效期必须大于0");
        }

        $params["surplus_num"] = $params["num"];
        $this->save($params);
        return true;
    }

    public function editCoupon($params){

        $rule = [
            ["title","require","请填写优惠券名称"],
            ["money","require","请填写满足金额"],
            ["reduction_money","require","请填写减免金额"],

        ];
        if(isset($params['type']) && $params['type'] == self::TYPE_PAY){
            $result[] = ["coupon_money","require","请填写优惠券金额"];
            if($params['coupon_money'] <= 0 ){
                exception("价格必须大于0");
            }
        }
        $validate = new Validate($rule);

        $result = $validate->check($params);
        if(!$result){
            exception((string)$validate->getError());
        }
        if($params['money'] <= 0 ){
            exception("满足金额必须大于0");
        }

        if($params['reduction_money'] <= 0 ){
            exception("减免金额必须大于0");
        }
        if($params['money'] <= $params['reduction_money'] ){
            exception("满足金额必须大于减免金额");
        }



        $this->save($params);
        return true;
    }


//    public function store()
//    {
//        return $this->belongsTo('app\admin\model\store\Store', 'store_id', 'id', [], 'LEFT')->setEagerlyType(0);
//    }


    //发送优惠券
    public function sendCoupon($users)
    {
        $userCouponModel = new UserCoupon();
        $usermodel = new User();
        if (!is_array($users)){
            $users = $usermodel->field('id')->where('id',$users)->select();
        }

        //检查是否足够
        if($this["surplus_num"] < count($users)){
            exception("优惠券数量不足");
        }

        $user_coupons = [];
        //给每个人发一张优惠券
        foreach ($users as $k=>$v){
            $user_coupons[] = [
                'user_id'=>$v['id'],
                'coupon_id'=>$this["id"],
                'status'=> self::STATUS_SEND,
                'money'=>$this['money'],
                'reduction_money'=>$this['reduction_money'],
                'type'=>$this['type'],
                'start_time'=>time(),
                'updatetime'=>time(),
                'createtime'=>time(),
                'end_time'=>strtotime("+{$this['day']} day"),
            ];
        }
        $userCouponModel->insertAll($user_coupons);

        //减数量
        $this->setDec("surplus_num", count($users));

    }


    /*
     * 检测是否领取过
     *
     * */
    public function checkReceive($user){
        if(is_null($user)){
            return false;
        }
        $count = UserCoupon::where("user_id", $user["id"])
            ->where("coupon_id", $this->id)
            ->count();
        if ($count >= 1) {
            return true;
        } else {
            return false;
        }

    }

    /*
    * 获取列表
    * */
    public function getList($user = null,$condition = [],$paginate = 1, $limit = 15){
        $list = $this->where($condition)->where("surplus_num", ">", 0)
            ->where("switch", 1)
            ->order("weigh", "desc");

        if($paginate == 1){
            $list = $list->paginate();
        }else{
            $list = $list->limit($limit)->select();
        }

        foreach ($list as $key => $value){
            $value['is_receive'] = $value->checkReceive($user);
        }
        return $list;
    }


    //优惠券详情
    public function getInfo($condition = []){
        $info = $this->where("surplus_num", ">", 0)
            ->where("switch", 1)
            ->where($condition)
            ->find();

        if(!$info){
            exception("未找到该优惠券");
        }
        return $info;
    }


    public function getUserCouponCount($user_id,$money = null){
        if($money){
            return UserCoupon::where("user_id",$user_id)
                ->where("status", $this::STATUS_SEND)
                ->where("money","<=", $money)
                ->count();
        }else{
            return UserCoupon::where("user_id",$user_id)
                ->where("status", $this::STATUS_SEND)
                ->count();
        }

    }
}
